package com.advertisementsystem.Controller;

import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.Servie.RoleService;
import com.advertisementsystem.Servie.UserService;
import com.advertisementsystem.entity.Role;
import com.advertisementsystem.entity.User;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
@Slf4j
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    private final UserService userService;
    private final RoleService roleService;

    /**
     * 获取所有角色列表
     */
    @GetMapping("/roles/list")
    public ResponseResult<List<Role>> getAllRoles() {
        List<Role> roles = roleService.getAllRoles();
        return ResponseResult.success(roles);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/users")
    public ResponseResult<IPage<User>> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {

        Page<User> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        // 关键字搜索
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(User::getUsername, keyword)
                    .or()
                    .like(User::getNickname, keyword)
                    .or()
                    .like(User::getEmail, keyword);
        }

        // 分页查询
        IPage<User> userPage = userService.page(page, queryWrapper);

        // 设置用户角色信息
        for (User user : userPage.getRecords()) {
            List<Role> roles = roleService.getRolesByUserId(user.getId());
            user.setRoles(roles);

            // 敏感信息处理
            user.setPassword(null);
        }

        return ResponseResult.success(userPage);
    }

    /**
     * 根据角色IDs获取所有用户IDs
     */
    @PostMapping("/users/by-roles")
    public ResponseResult<List<Long>> getUsersByRoles(@RequestBody RoleIdsRequest request) {
        if (request.getRoleIds() == null || request.getRoleIds().length == 0) {
            return ResponseResult.error("角色IDs不能为空");
        }

        List<Long> userIds = new ArrayList<>();

        for (Long roleId : request.getRoleIds()) {
            List<Long> ids = userService.getUserIdsByRoleId(roleId);
            userIds.addAll(ids);
        }

        // 去重
        userIds = userIds.stream().distinct().collect(Collectors.toList());

        return ResponseResult.success(userIds);
    }

    /**
     * 获取所有用户IDs
     */
    @GetMapping("/users/all-ids")
    public ResponseResult<List<Long>> getAllUserIds() {
        List<Long> userIds = userService.getAllUserIds();
        return ResponseResult.success(userIds);
    }

    /**
     * 角色IDs请求对象
     */
    static class RoleIdsRequest {
        private Long[] roleIds;

        public Long[] getRoleIds() {
            return roleIds;
        }

        public void setRoleIds(Long[] roleIds) {
            this.roleIds = roleIds;
        }
    }
}